<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Word/PDF转Markdown</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
        }
        .drop-area {
            border: 2px dashed #ccc;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            margin: 20px 0;
            color: #555;
            transition: all 0.3s;
        }
        .drop-area:hover {
            border-color: #aaa;
            background-color: #f9f9f9;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #45a049;
        }
        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .file-info {
            font-size: 12px;
            color: #777;
            margin-top: 4px;
        }
        .file-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 15px;
            margin: 8px 0;
            background-color: #f5f5f5;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .file-item button {
            margin-left: 10px;
        }
        .error-info {
            color: #d9534f;
            font-weight: bold;
        }
        .error-details {
            color: #a94442;
            font-size: 12px;
            background-color: #f2dede;
            border: 1px solid #ebccd1;
            border-radius: 3px;
            padding: 5px;
            margin-top: 5px;
            max-width: 600px;
            white-space: pre-wrap;
            word-break: break-word;
        }
        .file-item.error {
            background-color: #fff8f8;
            border-left: 3px solid #d9534f;
        }
        .status-info {
            font-size: 12px;
            color: #337ab7;
            margin-top: 5px;
        }
        .loading-spinner {
            display: inline-block;
            width: 12px;
            height: 12px;
            border: 2px solid rgba(0, 0, 0, 0.1);
            border-left-color: #4CAF50;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            vertical-align: middle;
            margin-left: 5px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <h1>Word/PDF转Markdown工具</h1>
    
    <div class="drop-area" id="dropArea">
        <p>拖拽Word或PDF文件到这里，或</p>
        <button id="selectFiles">选择文件</button>
        <input type="file" id="fileInput" multiple accept=".docx,.pdf" style="display: none;">
        <p class="file-info">支持格式：.docx, .pdf</p>
    </div>
    
    <div id="fileList"></div>
    
    <div style="text-align: center; margin-top: 20px;">
        <button id="convertBtn" onclick="convertFiles()" style="display: none;">开始转换</button>
        <button id="downloadAllBtn" onclick="downloadAllFiles()" style="display: none;">批量下载</button>
        <p class="file-info" style="margin-top: 15px;">注意：批量下载仅包含本次转换的文件</p>
    </div>
    
    <script>
        // 获取DOM元素
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const fileList = document.getElementById('fileList');
        const convertBtn = document.getElementById('convertBtn');
        const downloadAllBtn = document.getElementById('downloadAllBtn');
        
        // 存储文件和转换结果
        let files = [];
        let convertedFiles = [];
        
        // 文件选择按钮点击事件
        document.getElementById('selectFiles').addEventListener('click', () => {
            fileInput.click();
        });
        
        // 文件选择事件
        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });
        
        // 拖放事件
        dropArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropArea.style.backgroundColor = '#f0f0f0';
        });
        
        dropArea.addEventListener('dragleave', () => {
            dropArea.style.backgroundColor = '';
        });
        
        dropArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dropArea.style.backgroundColor = '';
            handleFiles(e.dataTransfer.files);
        });
        
        // 处理文件
        function handleFiles(newFiles) {
            for (let file of newFiles) {
                const extension = file.name.split('.').pop().toLowerCase();
                if (extension === 'docx' || extension === 'pdf') {
                    files.push(file);
                }
            }
            updateFileList();
        }
        
        // 更新文件列表
        function updateFileList() {
            fileList.innerHTML = '';
            files.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                
                const extension = file.name.split('.').pop().toLowerCase();
                const fileType = extension === 'docx' ? 'Word文档' : 'PDF文档';
                
                fileItem.innerHTML = `
                    <div>
                        <span>${file.name}</span>
                        <div class="file-info">${fileType} - ${formatFileSize(file.size)}</div>
                    </div>
                    <button onclick="removeFile(${index})">删除</button>
                `;
                fileList.appendChild(fileItem);
            });
            
            convertBtn.style.display = files.length > 0 ? 'inline-block' : 'none';
            downloadAllBtn.style.display = 'none';
        }
        
        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
            else return (bytes / 1048576).toFixed(1) + ' MB';
        }
        
        // 删除文件
        function removeFile(index) {
            files.splice(index, 1);
            updateFileList();
        }
        
        // 转换文件
        function convertFiles() {
            if (files.length === 0) return;

            // 显示加载状态
            fileList.innerHTML = '';
            files.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                    <div>
                        <span>${file.name}</span>
                        <div class="file-info">${file.type === 'docx' ? 'Word文档' : 'PDF文档'} - ${formatFileSize(file.size)}</div>
                        <div class="status-info">转换中... <span class="loading-spinner"></span></div>
                    </div>
                `;
                fileList.appendChild(fileItem);
            });

            // 准备表单数据
            const formData = new FormData();
            files.forEach(file => {
                formData.append('files[]', file);
            });

            // 发送请求
            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`服务器错误 (${response.status}): ${response.statusText}`);
                }
                return response.json();
            })
            .then(data => {
                // 更新UI显示转换结果
                fileList.innerHTML = '';
                convertedFiles = [];
                
                data.forEach(item => {
                    const fileItem = document.createElement('div');
                    fileItem.className = 'file-item';
                    
                    if (item.status === 'success') {
                        convertedFiles.push({
                            filename: item.md_filename,
                            originalName: item.original_name
                        });
                        
                        fileItem.innerHTML = `
                            <div>
                                <span>${item.filename}</span>
                                <div class="file-info">转换成功</div>
                            </div>
                            <button onclick="downloadFile('${item.md_filename}')">下载</button>
                        `;
                    } else {
                        fileItem.classList.add('error');
                        let errorMessage = item.message || '未知错误';
                        fileItem.innerHTML = `
                            <div>
                                <span>${item.filename}</span>
                                <div class="file-info error-info">转换失败</div>
                                <div class="error-details">错误信息: ${errorMessage}</div>
                            </div>
                        `;
                    }
                    
                    fileList.appendChild(fileItem);
                });
                
                if (convertedFiles.length > 0) {
                    downloadAllBtn.style.display = 'inline-block';
                }
                
                // 清空文件列表，准备下一次上传
                files = [];
                convertBtn.style.display = 'none';
            })
            .catch(error => {
                console.error('Error:', error);
                // 显示错误信息
                fileList.innerHTML = `
                    <div class="file-item error">
                        <div>
                            <span>转换过程中发生错误</span>
                            <div class="error-details">${error.message}</div>
                            <div class="file-info">请重试或联系管理员</div>
                        </div>
                    </div>
                `;
                files = [];
                convertBtn.style.display = 'none';
            });
        }
        
        // 单独下载文件
        function downloadFile(filename) {
            const downloadUrl = `/download/${filename}`;
            
            // 创建一个隐藏的下载链接
            const a = document.createElement('a');
            a.href = downloadUrl;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
        
        // 批量下载
        async function downloadAllFiles() {
            if (convertedFiles.length === 0) return;
            
            try {
                downloadAllBtn.innerHTML = '下载中<span class="loading-spinner"></span>';
                downloadAllBtn.disabled = true;
                
                // 使用GET请求而不是POST
                window.location.href = '/download-all';
                
            } catch (error) {
                alert('批量下载失败: ' + error.message);
                console.error('下载错误:', error);
            } finally {
                setTimeout(() => {
                    downloadAllBtn.innerHTML = '批量下载';
                    downloadAllBtn.disabled = false;
                }, 1000);
            }
        }
    </script>
</body>
</html> 